package com.huang.store.controller;

import cn.hutool.core.util.StrUtil;
import com.huang.enums.CommonCodeEnum;
import com.huang.resp.CommonResult;
import com.huang.store.bean.OssFile;
import com.huang.store.config.OssProperties;
import com.huang.store.core.MinioTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * OSS 文件处理
 *
 * @author han
 * @since 2022-04-19 11:17:15
 */
@RestController
@RequestMapping("miniOss")
public class OssController {

    private static final Logger logger = LoggerFactory.getLogger(OssController.class);

    @Resource
    private OssProperties ossProperties;
    @Resource
    private MinioTemplate minioTemplate;

    @PostMapping("upload")
    public CommonResult miniOss(@RequestParam("ossFile") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.error(CommonCodeEnum.PARAM_FILE_EMPTY_ERROR, "请上传文件！");
        }
        try {
            OssFile ossFile = minioTemplate.upload("oss-blog", file.getOriginalFilename(), file);
            String url = minioTemplate.getUrl(ossFile.getBucketName(), ossFile.getFileName());
            return CommonResult.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(CommonCodeEnum.PARAM_FILE_EMPTY_ERROR, e.getMessage());
        }
    }

    @GetMapping("getUrl")
    public CommonResult miniOss(@RequestParam("fileName") String fileName,
                                @RequestParam(value = "bucketName", required = false) String bucketName) {
        try {
            if (StrUtil.isBlank(bucketName)) {
                bucketName = ossProperties.getBucketName();
            }
            String url = minioTemplate.getUrl(bucketName, fileName);
            return CommonResult.success(url);
        } catch (Exception e) {
            logger.error("获取图片地址异常：", e);
            return CommonResult.error(e.getMessage());
        }
    }
}
